var lastVal = 0;

function colorize(val)
{
	if(val == null)
		val = 50;
	var delta = val - lastVal;
	var bright = 200;
	$("span.percent").text(val + '%');

	var newColor = 'rgb(' + Math.min(255, 5*(100 - val)) + ',' + Math.min(255, 5*val) + ', 0 )';
	$('#color').animate({ backgroundColor: newColor , width : Math.max(10, val) + '%'}, {duration : 2000, queue: false});
	var lightColor = 'rgb(' + Math.max(bright,Math.min(255, 5*(100 - val))) + ',' + Math.max(bright,Math.min(255, 5*val)) + ',' + bright + ')';
	$('#bgcolor').animate({ backgroundColor: lightColor , width: Math.min(90,(100 - val)) + '%' }, {duration : 2000, queue: false});
	
	allign();
	lastVal = val;
	return false;
}

function allign()
{
	var parent_height = $('#color span').parent().height();  
 	var image_height = $('#color span').height();  
 	var top_margin = (parent_height - image_height)/2;  
 	$('#color span').css( 'top' , top_margin);
	$('#bgcolor span').css( 'top' , top_margin);  
	
	var parent_width = $('#color span').parent().parent().width();  
	/*parent_width = 500;*/
	var image_width = $('#color span').width();    
	var left_margin = (parent_width - image_width)/2;  
	$('#color span').css( 'left' , left_margin);
	$('#bgcolor span').css( 'right' , left_margin);
}

var understand=0;
var totalStudents=0;

function refreshChartData(){
	$.getJSON('getStudentVotes', { topicKey : topics[currentTopic] }, function (data) {
		console.log("refreshChartData: good:"+data.voiceUnderstand+", all: "+data.voiceTotal);
		understand=data.voiceUnderstand;
		totalStudents=data.voiceTotal;
		var percentageUnderstand = (totalStudents > 0)?(understand / totalStudents) * 100 || 0 : 100;
		colorize(Math.round(percentageUnderstand));
	});
}

function startup() {
	refreshChartData()
	allign();
	setInterval(refreshChartData, 15000);
}
